
package com.x52im.mall;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.eva.framework.dto.DataFromClient;
import com.eva.framework.dto.DataFromServer;
import com.eva.framework.dto.SysActionConst;
import com.x52im.mall.dto.CommonProcessorConst;
import com.x52im.mall.logic.score.DBAdapter;
import com.eva.android.widget.DataLoadableActivity;
import com.eva.epc.common.util.CommonUtils;
import com.paypal.android.sdk.payments.PaymentActivity;
import com.paypal.android.sdk.payments.PaymentConfirmation;
import com.x52im.mall.score.dto.TokenRechangeHistory;
import com.x52im.mall.shop.dto.JobDispatchConst;
import com.x52im.mall.shop.dto.SO;
import com.x52im.rbchat.R;

public class CommonPaymentActivity extends DataLoadableActivity
{

	/**
	 * 购买设备
	 */
	public static String PAYPAL_PAYMENT_DEVICE = "__device__";
	/**
	 * 充值积分
	 */
	public static String PAYPAL_PAYMENT_INTEGRAL = "__integral__";
	
	public static final int PAYPAL_ANDROID_SDK_PAYMENT_RESULT = 999;
	public static final int PAYPAL_EXPRESS_CHECK_OUT_RESULT = 998;
	public static final int ALIPAY_RESULT = 997;

	private Button paypalSdkBtn = null;
	private Button paypalChkoutBtn = null;

	private SO so = null;
	
	private TokenRechangeHistory history = null;

	private static DBAdapter mDBAdapter;
	
	private String rechargeType;

	@Override
	protected void initDataFromIntent()
	{
		ArrayList datas = IntentFactory.parsePaymentActivityIntent(getIntent());
		so = datas.get(0) == null ? null : (SO) datas.get(0);
		history = datas.get(1) == null ? null : (TokenRechangeHistory)datas.get(1);
		rechargeType = (String)datas.get(2);
	}

	@Override
	protected void initViews(Bundle savedInstanceState)
	{

		customeTitleBarResId = R.id.common_payment_titleBar;

		// 首先设置contentview
		setContentView(R.layout.common_payment_view);
		// 设置标题
		this.setTitle("Payment");

		paypalSdkBtn = (Button) findViewById(R.id.common_payment_paypal_sdk);
		paypalChkoutBtn = (Button) findViewById(R.id.common_payment_express_checkout);

		startService(PayPalConfig.getPayPalServiceIntent(CommonPaymentActivity.this));
	}

	@Override
	protected void initListeners()
	{
		paypalSdkBtn.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if(rechargeType.equals(PAYPAL_PAYMENT_DEVICE))
				{
					String shortDesc = "Order num: " + so.getOrder_id();
					startActivityForResult(PayPalConfig.getPayPayActivityIntent(CommonPaymentActivity.this, so.getOrder_total(), "USD", shortDesc),
							PAYPAL_ANDROID_SDK_PAYMENT_RESULT);
				}
				else if(rechargeType.equals(PAYPAL_PAYMENT_INTEGRAL))
				{
					String shortDesc = history.getHistory_token() + "_" + MallGlobal.getMallProviderInstance(CommonPaymentActivity.this).getRobotimeMall().getLoginedUserUid();
					startActivityForResult(PayPalConfig.getPayPayActivityIntent(CommonPaymentActivity.this, history.getHistory_amount(), "USD", shortDesc),
							PAYPAL_ANDROID_SDK_PAYMENT_RESULT);
				}
			}
		});

		paypalChkoutBtn.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Map<String, String> parmas = new HashMap<String, String>();
				//表示购买设备
				if(rechargeType.equals(CommonPaymentActivity.PAYPAL_PAYMENT_DEVICE))
				{
					if (so != null)
					{
						parmas.put("cmd", "_xclick");// _xclick
						parmas.put("business", MallGlobal.getMallProviderInstance(CommonPaymentActivity.this).getRobotimeMall().getPayPalExpressCheckOutConfig()
								.get("__seller_acount__"));
						parmas.put("item_name", "EFEELINK - Shop");
						parmas.put("item_number", so.getOrder_id());
						parmas.put("amount", so.getOrder_total());
						parmas.put("currency_code", "USD");
						
						parmas.put("custom", rechargeType);
						parmas.put("invoice", so.getSign());
	
						String returnUrl = MallGlobal.getMallProviderInstance(CommonPaymentActivity.this).getRobotimeMall().getPayPalExpressCheckOutConfig()
								.get("__express_check_out_return_url__");
						
						parmas.put("return", returnUrl);
					}
	
					String url = MallGlobal.getMallProviderInstance(CommonPaymentActivity.this).getRobotimeMall().getPayPalExpressCheckOutConfig()
							.get("__express_check_out_url__");
					String data = Utility.convertMap2String(parmas);
					
					System.out.println("!!!!!!!!!!>>>>>>>url="+url);
					System.out.println("!!!!!!!!!!>>>>>>>data="+data);
					startActivityForResult(IntentFactory.createWebPostActivityIntent(CommonPaymentActivity.this, url, data), PAYPAL_EXPRESS_CHECK_OUT_RESULT);
				}
				//表示是积分充值
				else if(rechargeType.equals(CommonPaymentActivity.PAYPAL_PAYMENT_INTEGRAL))
				{
					if (history != null)
					{
						parmas.put("cmd", "_xclick");// _xclick
						parmas.put("business", MallGlobal.getMallProviderInstance(CommonPaymentActivity.this).getRobotimeMall().getPayPalExpressCheckOutConfig()
								.get("__seller_acount__"));
						parmas.put("item_name", "EFEELINK - Shop");
						parmas.put("item_number", history.getUser_uid() + "_" + history.getHistory_token());
						parmas.put("amount", history.getHistory_amount());
						parmas.put("currency_code", "USD");
						
						parmas.put("custom", rechargeType);
						//加密 目前积分无发票概念，生成随机码，支付处理端并不做验证。
						parmas.put("invoice", CommonUtils.getRandomStr2(20));
	
						String returnUrl = MallGlobal.getMallProviderInstance(CommonPaymentActivity.this).getRobotimeMall().getPayPalExpressCheckOutConfig()
								.get("__express_check_out_return_url__");
						
						parmas.put("return", returnUrl);
					}
	
					String url = MallGlobal.getMallProviderInstance(CommonPaymentActivity.this).getRobotimeMall().getPayPalExpressCheckOutConfig()
							.get("__express_check_out_url__");
					String data = Utility.convertMap2String(parmas);
					
					System.out.println("!!!!!!!!!!>>>>>>>url="+url);
					System.out.println("!!!!!!!!!!>>>>>>>data="+data);
					startActivityForResult(IntentFactory.createWebPostActivityIntent(CommonPaymentActivity.this, url, data), PAYPAL_EXPRESS_CHECK_OUT_RESULT);
				}
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		switch (requestCode)
		{
		case PAYPAL_ANDROID_SDK_PAYMENT_RESULT:
			doPayPalSDKResult(resultCode, data);
			break;

		case PAYPAL_EXPRESS_CHECK_OUT_RESULT:
			doPayPalExpressCheckOutResult(resultCode, data);
		default:
			break;
		}

	}

	/**
	 * 使用PayPal Android SDK集成付款
	 * @param resultCode
	 * @param data
	 */
	private void doPayPalSDKResult(int resultCode, Intent data)
	{
		if (resultCode == Activity.RESULT_OK)
		{
			PaymentConfirmation confirm = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
			if (confirm != null)
			{
				try
				{
					Log.i("payment", confirm.toJSONObject().toString(4));
					System.out.println(confirm.toJSONObject().toString(4));
					JSONObject confirmObj = confirm.toJSONObject().getJSONObject("proof_of_payment");
					JSONObject adaptivePayment = confirmObj.has("adaptive_payment") ? confirmObj.getJSONObject("adaptive_payment") : null;
					JSONObject restApi = confirmObj.has("rest_api") ? confirmObj.getJSONObject("rest_api") : null;

					String payTime = "";
					String payKey = "";
					boolean isSucceed = false;

					// PayPal账户支付
					if (!isSucceed && adaptivePayment != null && adaptivePayment.getString("payment_exec_status").equalsIgnoreCase("completed"))
					{
						payTime = adaptivePayment.getString("timestamp").substring(0, adaptivePayment.getString("timestamp").indexOf("+")).replace("T", " ");
						payKey = adaptivePayment.getString("pay_key");
						isSucceed = true;
					}

					// 信用卡支付
					if (!isSucceed && restApi != null && restApi.getString("state").equalsIgnoreCase("approved"))
					{
						payTime = "";
						payKey = adaptivePayment.getString("payment_id");
						isSucceed = true;
					}

					if (isSucceed)
					{
						if(rechargeType.equals(CommonPaymentActivity.PAYPAL_PAYMENT_DEVICE))
						{
							so.setPay_time(payTime);
							so.setPay_key(payKey);
							// 1.为已付款待发货
							so.setOrder_status("1");
	
							String jsonStr = JSON.toJSONString(so, true);
	
							mDBAdapter = new DBAdapter(getApplication());
							mDBAdapter.open();
							String keyId = mDBAdapter.insert(jsonStr, SO.class.getCanonicalName()) + "";
							mDBAdapter.close();
	
							new CommonDataAsync(CommonPaymentActivity.this)
							{
								@Override
								protected DataFromClient forDoInBackground(String param, String clsName)
								{
									return DataFromClient.n().setProcessorId(CommonProcessorConst.PROCESSOR_SHOP_NEED$AUTHED)
											.setJobDispatchId(JobDispatchConst.SHOP_GOODS_MGR_NEED$AUTHED).setActionId(SysActionConst.ACTION_EDIT)
											.setNewData(JSON.parseObject(param, SO.class));
								}
	
								@Override
								protected void forOnPostExecute(DataFromServer dfs, String keyId)
								{
									// 服务端的返回值对象
									if (dfs != null && dfs.isSuccess())
									{
										mDBAdapter = new DBAdapter(getApplication());
										mDBAdapter.open();
										mDBAdapter.delete(keyId);
										mDBAdapter.close();
										setResult(Activity.RESULT_OK);
									}
									else
									{
										setResult(Activity.RESULT_CANCELED);
									}
									finish();
								}
							}.execute(new String[] { keyId, jsonStr });
							setResult(Activity.RESULT_OK);
							finish();
						}
						else if(rechargeType.equals(CommonPaymentActivity.PAYPAL_PAYMENT_INTEGRAL))
						{
							history.setAppender(payTime);
							history.setPay_key(payKey);

							String jsonStr = JSON.toJSONString(history, true);
							mDBAdapter = new DBAdapter(getApplication());
							mDBAdapter.open();
							String keyId = mDBAdapter.insert(jsonStr, TokenRechangeHistory.class.getCanonicalName()) + "";
							mDBAdapter.close();
							
							new CommonDataAsync(CommonPaymentActivity.this)
							{
								@Override
								protected DataFromClient forDoInBackground(String param,String clsName)
								{
									return DataFromClient.n().setProcessorId(CommonProcessorConst.PROCESSOR_SCORE)
											.setJobDispatchId(com.x52im.mall.score.dto.JobDispatchConst.SCORE_RECHARGE_ETC)
											.setActionId(SysActionConst.ACTION_NEW)
											.setNewData(JSON.parseObject(param, TokenRechangeHistory.class));
								}

								@Override
								protected void forOnPostExecute(DataFromServer dfs, String keyId)
								{
									int resId;
									// 服务端的返回值对象
									if (dfs != null && dfs.isSuccess())
									{
										mDBAdapter = new DBAdapter(getApplication());
										mDBAdapter.open();
										mDBAdapter.delete(keyId);
										mDBAdapter.close();
										resId = R.string.common_mall_recharge_score_pay_success;
									}
									else
									{
										resId = R.string.common_mall_recharge_score_pay_failure;
									}
									Toast.makeText(CommonPaymentActivity.this, resId, Toast.LENGTH_LONG).show();
								}
							}.execute(new String[] { keyId, jsonStr });
							
							setResult(Activity.RESULT_OK);
							finish();
						}
						else
						{
	
						}
					}
					else
					{

					}
				}
				catch (JSONException e)
				{
					Log.e("payment", "JSON数据转换发生故障: ", e);
				}
			}
		}
		else if (resultCode == Activity.RESULT_CANCELED)
		{
			Log.i("payment", "用户已取消付款");
		}
		else if (resultCode == PaymentActivity.RESULT_PAYMENT_INVALID)
		{
			Log.i("payment", "一个无效的支付被提交。请见文档。");
		}
	}
	
	/**
	 * 使用PayPal快速结账支付
	 * @param resultCode
	 * @param data
	 */
	private void doPayPalExpressCheckOutResult(int resultCode, Intent data)
	{
		if (resultCode == Activity.RESULT_OK)
		{
			setResult(Activity.RESULT_OK);
			finish();
		}
	}

	@Override
	protected DataFromServer queryData(String... arg0)
	{
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected void refreshToView(Object arg0)
	{
		// TODO Auto-generated method stub

	}
}
